package com.dongdongshop.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.mapper.TbAddressMapper;
import com.dongdongshop.mapper.TbUserMapper;
import com.dongdongshop.pojo.user.TbAddress;
import com.dongdongshop.pojo.user.TbAddressExample;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.pojo.user.TbUserExample;
import com.dongdongshop.service.user.UserService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Service
@Component
public class UserServiceImpl implements UserService {

    @Resource
    private TbUserMapper tbUserMapper;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private TbAddressMapper tbAddressMapper;

    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public TbUser getUserByUserName(String username) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> tbUsers = tbUserMapper.selectByExample(example);
        if (tbUsers.size() > 0){
            return tbUsers.get(0);
        }
        return null;
    }

    //用户注册
    @Override
    public void addUser(TbUser user) {
        tbUserMapper.insertSelective(user);
    }

    //调用 rocketMq进行发送消息
    @Override
    public String sendMessage(String phoneNumber) {
        try {
            rocketMQTemplate.convertAndSend("MyTopic",phoneNumber);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    @Override
    public Boolean checkCodeByPhone(String phone, String code) {
        String PhoneCheckCodeRedisKey = phone+code;
        return  redisTemplate.hasKey(PhoneCheckCodeRedisKey);
    }

    @Override
    public TbUser getByUser(Long id) {
        return tbUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TbUser> getByName(String username) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> tbUsers = tbUserMapper.selectByExample(example);
        return tbUsers;
    }

    @Override
    public void updatePwdandSalt(TbUser user) {
        tbUserMapper.updateByPrimaryKeySelective(user);
    }
}
